package com.ys.controller.api.storage;

import com.alibaba.fastjson.JSON;
import com.ys.config.MenuId;
import com.ys.entity.storage.TccFbaBoxUp;
import com.ys.entity.storage.TccFbaCancel;
import com.ys.entity.sys.YsCol;
import com.ys.service.storage.TccFbaCancelService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.CheckUtil;
import com.ys.util.ExportExcelUtils;
import com.ys.util.ToolUtil;
import com.ys.util.admin.ConditionUtil;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * FBA取消单
 */
@Controller
@RequestMapping("/api/inter/tccFbaCancel")
public class ApiInterTccFbaCancelController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTccFbaCancelController.class);

    @Autowired
    private CommonApiService<TccFbaCancel> commonApiService;

    @Autowired
    private TccFbaCancelService tccFbaCancelService;

    @Autowired
    private CheckUtil checkUtil;

    //菜单id
    private Long menuId = MenuId.TCC_FbaCancel;
    private Long menuId_doCancel = MenuId.TCC_FbaCancel_DoCancel;

    //权限字符
    private final String PERMISSIONS_VIEW = "tccFbaCancel:view";
    private final String PERMISSIONS_PASS = "tccFbaCancel:passCancel";//取消确认
    private final String PERMISSIONS_NO = "tccFbaCancel:noCancel";//暂不取消



    /**
     * 取消确认保存
     */
    //@RequiresPermissions(PERMISSIONS_PASS)
    @RequestMapping("/passCancel")
    @ResponseBody
    public R passCancel(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            return tccFbaCancelService.passCancel(params);
        } catch (IllegalArgumentException e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        } catch (RuntimeException e){
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 取消确认保存-FBA计划取消带子列表
     */
    //@RequiresPermissions(PERMISSIONS_PASS)
    @RequestMapping("/passCancelWithGrid")
    @ResponseBody
    public R passCancelWithGrid(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            return tccFbaCancelService.passCancelWithGrid(params);
        } catch (IllegalArgumentException e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        } catch (RuntimeException e){
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }





//
//    /**
//     * 设置查询的cond的sql设置
//     * @param cond
//     * @return
//     */
//    public TccFbaCancel setSeachSql(TccFbaCancel cond) throws Exception{
//
//        cond
//                    .addField("FORMAT(A.ExamineTime, 'yyyy-MM-dd HH:mm:ss') AS examineTimeByFormat")//审核时间
//                .addLeftJoin("TS_UserChange B ON B.Id = A.ExamineChangeId ")
//                    .addField("B.UserId + '/' + B.UserName AS _ys_examineUserName")//审核人
//                .addLeftJoin("TS_UserChange AC ON AC.Id = A.CreateChangeId ")//制单人表
//
//                .addLeftJoin("TCC_FbaCancelItem FI ON A.Bid = FI.BidCancel ")//FBA取消单子件信息
//                .addField("FI.ShipmentState AS shipmentState")//货件状态
//                .addField("FI.BidFbaBoxUp AS bidFbaBoxUp")//FBA装箱单号
//                .addField("FI.BidFbaDelivery AS bidFbaDelivery")//FBA发货单号
//
//
//                //****** 计划单信息 ******
//                .addLeftJoin("TCC_FbaPlan FB ON A.BidFbaPlan = FB.Bid")//FBA计划单
//                    .addField("FB.CreationMethod AS creationMethod")//下单方式(0.手动|1.自动)
//                    .addField("FB.DeclarationState AS declarationState")//是否报关（1是，0否）
//                    .addField("FB.DeliverState AS deliverState")//发货计划（1按SKU自动发货，0按箱自动发货）
//                    .addField("FB.Vgsbm AS vgsbm")//运营公司编码
//                    .addField("FB.VgsJc AS vgsJc")//运营公司简称
//                    .addField("FB.ShopName AS shopName")//网店名称
//                    .addField("FB.Remark AS remarkByFbaPlan")//本单备注
//
//                .addLeftJoin("TS_UserChange FBUC ON FBUC.Id = FB.CreateChangeId ")//FBA计划单制单人表
//                .addField("FBUC.UserId + '/' + FBUC.UserName AS _ys_createUserNameByFbaPlan")//制单人
//
//                .addLeftJoin("TCC_FbaPlanItem FA ON FA.BidFbaPlan = FB.Bid")//Fba计划子件
//                .addField("FA.CommodityCode AS commodityCode")//商品编码
//                .addField("FA.CommodityName AS commodityName")//商品名称
//                .addField("FA.Sku AS sku")//SKU
//                .addField("FA.NumStock AS numStock")//库存可用数量
//                .addField("FA.NumPlanDeliver AS numPlanDeliver")//计划发货数量
//                .addField("FA.IsSign AS isSign")//透明标记(是/否
//                .addField("FA.SignCode AS signCode")//透明计划标签编码
//                .addField("FA.AnnexFile AS annexFileByPlanItem")//透明标签附件
//                .addField("FA.Asin AS asin")//ASIN
//                .addField("FA.FnSku AS fnSku")//FNSKU
//                .addField("FA.CodeGoodsHs AS codeGoodsHs")//海关编码
//                .addField("FA.NameGoodsCn AS nameGoodsCn")//商品品名（中文）
//                .addField("FA.NameMaterialCn AS nameMaterialCn")//商品材质（中文）
//                .addField("FA.PriceIn AS priceIn")//商品采购价
//                .addField("(CAST(FA.lengthPackage AS varchar) + '*' + CAST(FA.widthPackage AS varchar) + '*' + CAST(FA.heightPackage AS varchar)) packageSize")//商品包装尺寸（cm）
//                .addField("FA.WeightPackage AS weightPackage")//商品重量（g）
//                .addField("FA.Vck AS vck")//仓库
//                .addField("FA.Vkq AS vkq")//库区
//                .addField("FA.Vhw AS vhw")//货位
//
//                .addLeftJoin("TCC_FbaLogisticsMethod FC ON FC.sourceBid = FB.Bid AND FC.sourceType = 0")
//                    .addField("FC.LogsticsWay AS logsticsWay")//物流方式
//                    .addField("FC.Vck AS vckByLogisticsMethod")//发货仓库
//
//                .addLeftJoin("TCC_FbaFeeDetails FD ON FD.sourceBid = FB.Bid AND FD.sourceType = 0")
//                    .addField("FD.PriceTranPredict AS priceTranPredict")//预估物流费（总）
//
//
//                //****** 装箱单信息 ******
//                .addLeftJoin("TCC_FbaBoxUp FBU ON FBU.Bid = FI.BidFbaBoxUp")
//                .addField("FBU.DistributionBid AS distributionBid") //配货清单号
//
//                .addLeftJoin("TCC_FbaBoxUpItem C ON C.BidBoxUp = FBU.Bid")//装箱单子列表
//                .addField("C.Id AS fbaBoxUpItemId") //装箱单子列表id
//                .addField("C.BidFbaPlan AS bidFbaPlan") //FBA计划单号
//                .addField("C.TagStateGoods AS tagStateGoods") //商品标打印状态
//                .addField("C.TagStateTransparent AS tagStateTransparent") //透明标打印状态
//                .addField("C.TagStateEur AS tagStateEur") //欧代标打印状态
//                .addField("C.GoodsLink AS goodsLink") //商品链接
//
//                .addLeftJoin("TCC_FbaBoxUpInfo D ON D.FbaBoxUpItemId = C.Id AND D.IsFirstRow = 1")//装箱单FBA信息表,只获取第一条信息
//                .addField("D.FbaNo AS fbaNo") //FBA编号
//                .addField("D.FbaTrackNo AS fbaTrackNo") //FBA追踪编号
//                .addField("D.FbaWarehouse AS fbaWarehouse") //FBA仓库
//                .addField("D.FbaWarehouseAddr AS fbaWarehouseAddr") //FBA仓库地址
//                .addField("D.FbaAmount AS fbaAmount") //FBA费用
//                .addField("D.BoxUpNum AS boxUpNum") //装箱数量
//
//                //获取装箱人
//                .addLeftJoin("TS_UserChange G ON G.Id = FBU.BoxUpChangeId")
//                .addField("G.UserId + '/' + G.UserName AS _ys_boxUpUser")//装箱人
//
//                //箱子信息
//                .addLeftJoin("TCC_FbaBoxDetail FDUB ON FDUB.BoxUpItemId = C.Id")
//                .addField("FDUB.Num AS boxDetailNum") //箱中数量
//                .addLeftJoin("TCC_FbaBox FDUC ON FDUC.Id = FDUB.BoxId")//装箱单子列表
//                .addField("(CAST(FDUC.BoxLong AS varchar) + '*' +  CAST(FDUC.BoxWide AS varchar)  + '*' + CAST(FDUC.BoxHigh AS varchar)) boxSize") //箱尺寸（长*宽*高）
//                .addField("FDUC.BoxWeight AS boxWeight") //箱重量
//
//
//                //****** 发货单信息 ******
//                .addLeftJoin("TCC_FbaDeliverItem FDU ON FDU.FbaBoxDetailId = FDUB.Id")//FBA发货单
//                .addField("FDU.BoxNo AS fbaDeliverBoxNo") //箱号
//
//                ;
//        //排序
//        cond.setOrderby("A.Bid DESC");
//        //权限
//        cond = commonApiService.dataAuth(menuId, cond);
//        return  cond;
//    }
//
//
//    /**
//     * 查询
//     */
//    @RequiresPermissions(PERMISSIONS_VIEW)
//    @RequestMapping("/search")
//    @ResponseBody
//    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
//                                 @ModelAttribute TccFbaCancel cond,String conditions
//    ){
//        try {
//            cond = setSeachSql(cond);
//            //查询条件
//            String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_examineUserName");//审核人
//            if (nameLinked != null){
//                cond.where("B.UserId LIKE '%" + nameLinked + "%'" + " OR  B.UserName LIKE '%" + nameLinked + "%'");
//            }
//            String boxUpUserLinked = ConditionUtil.getConditionValue(conditions, "_ys_boxUpUser");//装箱人
//            if (boxUpUserLinked != null){
//                cond.where("G.UserId LIKE '%" + boxUpUserLinked + "%'" + " OR  G.UserName LIKE '%" + boxUpUserLinked + "%'");
//            }
//            String createUserNameByFbaPlan = ConditionUtil.getConditionValue(conditions, "_ys_createUserNameByFbaPlan");//FBA计划单制单人
//            if (createUserNameByFbaPlan != null){
//                cond.where("FBUC.UserId LIKE '%" + createUserNameByFbaPlan + "%'" + " OR  FBUC.UserName LIKE '%" + createUserNameByFbaPlan + "%'");
//            }
//
//
//
//            LayuiTableVoJA setList = commonApiService.searchLay(cond);
//            return setList;
//        }catch (Exception e){
//            logger.error("查询出错：",e.getMessage(),e);
//            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
//            tableVoJA.setCode(1);
//            tableVoJA.setMsg("查询出错，请稍后重试！");
//            return tableVoJA;
//        }
//    }
//
//    /**
//     * 导出
//     */
//    @RequestMapping("/export")
//    @ResponseBody
//    public R export(@ModelAttribute TccFbaCancel cond,String conditions){
//        try {
//            cond.setPage(0).setSize(999999);
//            cond = setSeachSql(cond);
//            String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_examineUserName");//审核人
//            if (nameLinked != null){
//                cond.where("B.UserId LIKE '%" + nameLinked + "%'" + " OR  B.UserName LIKE '%" + nameLinked + "%'");
//            }
//            String boxUpUserLinked = ConditionUtil.getConditionValue(conditions, "_ys_boxUpUser");//装箱人
//            if (boxUpUserLinked != null){
//                cond.where("G.UserId LIKE '%" + boxUpUserLinked + "%'" + " OR  G.UserName LIKE '%" + boxUpUserLinked + "%'");
//            }
//            String createUserNameByFbaPlan = ConditionUtil.getConditionValue(conditions, "_ys_createUserNameByFbaPlan");//FBA计划单制单人
//            if (createUserNameByFbaPlan != null){
//                cond.where("FBUC.UserId LIKE '%" + createUserNameByFbaPlan + "%'" + " OR  FBUC.UserName LIKE '%" + createUserNameByFbaPlan + "%'");
//            }
//
//            //获取菜单字段数据
//            List<YsCol> listField = new YsCol()
//                    .setMenuId(menuId)
//                    .setFrontShow(1)
//                    .setOrderby("A.SortNo asc")
//                    .queryList();
//            //获取数据
//            List<Map<String, Object>> listData = cond.queryMap();
//            //处理数据
//            ExportExcelUtils<TccFbaBoxUp> util = new ExportExcelUtils<>(new TccFbaBoxUp());
//            String toFilePath = util.exportExcel(listData, listField, "FBA取消单");
//            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
//            return R.ok(dto.getUrl());
//        }catch (Exception e){
//            logger.error("导出出错：",e.getMessage(),e);
//            return R.error("导出失败，请稍后重试！");
//        }
//    }
//
//
//
//
//    /**
//     * 取消确认 - 未配货
//     */
//    @RequiresPermissions(PERMISSIONS_PASS)
//    @RequestMapping("/passCancelByNoPrepare")
//    @ResponseBody
//    public R passCancelByNoPrepare(HttpServletRequest request, @RequestParam Map<String, Object> params){
//        try {
//            return tccFbaCancelService.passCancel(params,menuId_doCancel,false,false);
//        } catch (IllegalArgumentException e) {
//            logger.error("出错：",e.getMessage(),e);
//            return R.error(e.getMessage());
//        } catch (RuntimeException e){
//            logger.error("出错：",e.getMessage(),e);
//            return R.error(e.getMessage());
//        } catch (Exception e) {
//            logger.error("出错：",e.getMessage(),e);
//            return R.error(e.getCause().getMessage());
//        }
//    }
//
//
//
//    /**
//     * 暂不取消
//     */
//    @RequiresPermissions(PERMISSIONS_NO)
//    @RequestMapping("/noCancel")
//    @ResponseBody
//    public R noCancel(HttpServletRequest request, @RequestParam Map<String, Object> params){
//        try {
//            //获取数据
//            String choooseDatas = params.get("choooseDatas").toString();
//            //根据单号去重
//            String groupStr = "bid";
//            List<Map<String, Object>> detailList = ToolUtil.groupsByJSONArray(JSON.parseArray(choooseDatas), e->e.get(groupStr).toString());
//            int doCount = 0;
//            StringBuilder resMsg = new StringBuilder();
//            for (int i = 0; i < detailList.size(); i++) {
//                Map<String, Object> info = detailList.get(i);
//                //处理
//                R res = tccFbaCancelService.noCancel(info.get(groupStr).toString());
//                if(res.getCode()==0){
//                    doCount ++;
//                }else{
//                    resMsg.append((info.get(groupStr)!=null?"单号："+info.get(groupStr):""))
//                            .append("；")
//                            .append(res.getMsg())
//                            .append("</br>");
//                }
//            }
//            resMsg.append("成功暂不取消").append(doCount).append("条数据</br>").append(resMsg);
//            return R.ok(resMsg);
//        } catch (Exception e) {
//            logger.error("出错：",e.getMessage(),e);
//            return R.error(e.getCause().getMessage());
//        }
//    }
//
//




}